<template>
  <view class="warehouse-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">入库作业</text>
    </view>

    <!-- 入库信息区域 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">入库信息</text>
      </view>

      <!-- 入库类型标签页 -->
      <view class="in-type-tabs">
        <view
          class="tab-item"
          :class="{ active: currentInType === 'weigh' }"
          @click="switchInType('weigh')"
        >
          <text class="tab-text">检斤入库</text>
        </view>
        <view
          class="tab-item"
          :class="{ active: currentInType === 'purchase' }"
          @click="switchInType('purchase')"
        >
          <text class="tab-text">采购入库</text>
        </view>
        <view
          class="tab-item"
          :class="{ active: currentInType === 'manual' }"
          @click="switchInType('manual')"
        >
          <text class="tab-text">人工入库</text>
        </view>
      </view>

      <view class="info-form">
        <view class="form-item">
          <text class="form-label">入库日期</text>
          <picker
            mode="date"
            :value="formData.queryDate"
            @change="handleDateChange"
          >
            <view class="warehouse-picker">
              <text class="warehouse-display">{{ formData.queryDate }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">目标仓库</text>
          <view class="warehouse-display">{{
            currentWarehouse ? currentWarehouse.warehouseName : "请选择"
          }}</view>
        </view>
      </view>
    </view>

    <!-- //物料编码查询，使用统一的扫码组件 -->
    <!-- 使用统一扫码输入组件 -->
    <view class="material-section">
      <view class="scan-section">
        <ScanInput
          v-model="searchForm.materialCode"
          placeholder="请输入物料编码或扫码"
          tip-text="物料扫码查询"
          :loading="isLoading"
          :on-scan-result="handleMaterialScanResult"
          :on-confirm="handleMaterialScanResult"
          ref="scanInputRef"
        />
      </view>
    </view>

    <!-- 合同查询 - 在采购入库、检斤入库、采购入库和人工入库模式下都显示 -->
    <view
      class="material-section"
      v-if="currentInType === 'purchase' || currentInType === 'weigh'"
    >
      <view class="section-header">
        <text class="section-title">合同查询</text>
        <!-- 第一行：时间筛选按钮组 -->
        <view class="time-filter-buttons">
          <button
            class="filter-btn"
            :class="{ active: contractTimeFilter === 'today' }"
            @click="handleContractTimeChange('today')"
          >
            当日
          </button>
          <button
            class="filter-btn"
            :class="{ active: contractTimeFilter === 'week' }"
            @click="handleContractTimeChange('week')"
          >
            本周
          </button>
          <button
            class="filter-btn"
            :class="{ active: contractTimeFilter === 'month' }"
            @click="handleContractTimeChange('month')"
          >
            本月
          </button>
        </view>
      </view>
      <!-- 合同匹配表格 - 采用stockIn.vue样式 -->
      <view
        class="contract-table-section"
        v-if="showContractTable && contractTable.length > 0"
      >
        <scroll-view
          class="table-scroll"
          scroll-y
          scroll-x
          @scrolltolower="loadMoreContracts"
          @scroll="handleTableScroll"
          ref="contractTableScroll"
        >
          <view class="table-scroll-container">
            <view class="table-scroll-wrapper">
              <view class="table-content">
                <view class="table-row header">
                  <text class="table-cell select-col">选择</text>
                  <text class="table-cell">合同编号</text>
                  <text class="table-cell">物料编码</text>
                  <text class="table-cell">物料名称</text>
                  <text class="table-cell">规格</text>
                  <text class="table-cell">数量</text>
                  <text class="table-cell">厂家</text>
                  <text class="table-cell">图号</text>
                  <text class="table-cell">创建时间</text>
                  <text class="table-cell">单价</text>
                  <text class="table-cell">金额</text>
                  <text class="table-cell">品牌</text>
                  <text class="table-cell">材质</text>
                  <text class="table-cell">标准</text>
                </view>
                <view
                  v-for="(item, index) in contractTable.slice(
                    0,
                    contractPageSize * contractCurrentPage
                  )"
                  :key="index"
                  class="table-row"
                  :class="{
                    selected:
                      selectedContract && selectedContract.id === item.id,
                  }"
                  @click="selectContract(item)"
                >
                  <view class="table-cell select-col">
                    <view class="custom-checkbox" @click="selectContract(item)">
                      <view
                        class="checkbox-icon"
                        :class="{
                          'checkbox-checked':
                            selectedContract && selectedContract.id === item.id,
                        }"
                      >
                        <text
                          v-if="
                            selectedContract && selectedContract.id === item.id
                          "
                          class="check-mark"
                          >✓</text
                        >
                      </view>
                    </view>
                  </view>
                  <text class="table-cell" :title="item.poContractDetailCode">{{
                    item.poContractDetailCode
                  }}</text>
                  <text class="table-cell" :title="item.materialCode">{{
                    item.materialCode || "-"
                  }}</text>
                  <text class="table-cell" :title="item.materialName">{{
                    item.materialName
                  }}</text>
                  <text class="table-cell" :title="item.spec">{{
                    item.spec || "-"
                  }}</text>
                  <text class="table-cell">{{ item.prodCount }}</text>
                  <text class="table-cell" :title="item.prodCompany">{{
                    item.prodCompany || "-"
                  }}</text>
                  <text class="table-cell" :title="item.picNo">{{
                    item.picNo || "-"
                  }}</text>
                  <text class="table-cell">{{
                    dateHelperApi.formatDate(item.createTime)
                  }}</text>
                  <text class="table-cell">{{ item.prodPrice || "-" }}</text>
                  <text class="table-cell">{{ item.budgetAmount || "-" }}</text>
                  <text class="table-cell" :title="item.brand">{{
                    item.brand || "-"
                  }}</text>
                  <text class="table-cell" :title="item.steelGradeName">{{
                    item.steelGradeName || "-"
                  }}</text>
                  <text class="table-cell" :title="item.standardName">{{
                    item.standardName || "-"
                  }}</text>
                </view>
              </view>
            </view>
            <view
              class="scroll-hint"
              :class="{ show: showContractScrollHint }"
              v-if="showContractScrollHint"
            >
              <text class="hint-icon">→</text>
              <text>横向滑动查看更多信息</text>
            </view>
          </view>
        </scroll-view>

        <!-- 加载更多 -->
        <view
          v-if="contractTable.length > contractPageSize * contractCurrentPage"
          class="load-more"
          @click="loadMoreContracts"
        >
          <text class="load-more-text">点击加载更多</text>
        </view>
      </view>
    </view>

    <!--计量单区域（根据入库类型动态显示） -->
    <view class="material-section">
      <!-- 检斤入库搜索 - 仅在检斤入库模式下显示 -->
      <view v-if="currentInType === 'weigh'" class="search-form">
        <view class="section-header">
          <text class="section-title">计量单</text>
          <!-- 时间筛选按钮组 -->
          <view class="time-filter-buttons">
            <button
              class="filter-btn"
              :class="{ active: weighTimeFilter === 'today' }"
              @click="handleWeighTimeChange('today')"
            >
              当日
            </button>
            <button
              class="filter-btn"
              :class="{ active: weighTimeFilter === 'week' }"
              @click="handleWeighTimeChange('week')"
            >
              本周
            </button>
            <button
              class="filter-btn"
              :class="{ active: weighTimeFilter === 'month' }"
              @click="handleWeighTimeChange('month')"
            >
              本月
            </button>
          </view>
        </view>
        <view class="section-header">
          <input
            class="material-input"
            type="text"
            v-model="searchForm.materialName"
            placeholder="请输入物料名称"
          />
          <button class="scan-btn" @click="searchWeighData">查询</button>
        </view>
      </view>
    </view>

    <!-- 检斤记录表格 - 采用stockIn.vue样式 -->
    <view
      class="weight-table-section"
      v-if="
        currentInType === 'weigh' && showWeightTable && weightTable.length > 0
      "
      :class="{ 'selected-table': selectedWeightRows.length > 0 }"
    >
      <scroll-view
        class="table-scroll"
        scroll-y
        scroll-x
        @scrolltolower="loadMoreWeights"
        @scroll="handleWeightTableScroll"
        ref="weightTableScroll"
      >
        <view class="table-scroll-container">
          <view class="table-scroll-wrapper">
            <view class="table-row header">
              <text class="table-cell select-col">选择</text>
              <text class="table-cell">物料</text>
              <text class="table-cell">净重(KG)</text>
              <text class="table-cell">数量</text>
              <text class="table-cell">车号</text>
              <text class="table-cell">供应商</text>
              <text class="table-cell">业务类型</text>
              <text class="table-cell">计量id</text>
              <text class="table-cell">皮重(KG)</text>
              <text class="table-cell">毛重(KG)</text>
              <text class="table-cell">司磅员</text>
              <text class="table-cell">收货仓库</text>
              <text class="table-cell">备注</text>
            </view>
            <view
              v-for="item in weightTable.slice(
                0,
                weightPageSize * weightCurrentPage
              )"
              :key="item.id"
              class="table-row"
              :class="{
                selected: selectedWeightRows.some((row) => row.id === item.id),
              }"
              @click="toggleWeightSelection(item)"
            >
              <view class="table-cell select-col">
                <view
                  class="custom-checkbox"
                  @click="toggleWeightSelection(item)"
                >
                  <view
                    class="checkbox-icon"
                    :class="{
                      'checkbox-checked': selectedWeightRows.some(
                        (row) => row.id === item.id
                      ),
                    }"
                  >
                    <text
                      v-if="
                        selectedWeightRows.some((row) => row.id === item.id)
                      "
                      class="check-mark"
                      >✓</text
                    >
                  </view>
                </view>
              </view>

              <text class="table-cell" :title="item.materialName">{{
                item.materialName || "-"
              }}</text>
              <text class="table-cell">{{ item.netWeight || "" }}</text>

              <view class="table-cell quantity-cell">
                <input
                  type="number"
                  v-model="item.quantity"
                  @input="updateWeightStatistics"
                  class="quantity-input"
                  placeholder="请输入数量"
                />
              </view>
              <text class="table-cell" :title="item.carNo">{{
                item.carNo || "-"
              }}</text>
              <text class="table-cell" :title="item.supplierName">{{
                item.supplierName || "-"
              }}</text>
              <text class="table-cell">{{ item.meterType || "-" }}</text>
              <text class="table-cell">{{ item.id || "-" }}</text>
              <text class="table-cell">{{ item.tareWeight || "-" }}</text>
              <text class="table-cell">{{ item.grossWeight || "-" }}</text>
              <text class="table-cell" :title="item.operatorName">{{
                item.operatorName || "-"
              }}</text>
              <text class="table-cell" :title="item.warehouseName">{{
                item.warehouseName || "-"
              }}</text>
              <text class="table-cell" :title="item.remark">{{
                item.remark || "-"
              }}</text>
            </view>
          </view>
          <!-- 滚动提示 -->
          <view
            class="scroll-hint"
            :class="{ show: showWeightScrollHint }"
            v-if="showWeightScrollHint"
          >
            <text class="hint-icon">→</text>
            <text>横向滑动查看更多信息</text>
          </view>
        </view>
      </scroll-view>

      <!-- 加载更多 -->
      <view
        v-if="weightTable.length > weightPageSize * weightCurrentPage"
        class="load-more"
        @click="loadMoreWeights"
      >
        <text class="load-more-text">点击加载更多</text>
      </view>
    </view>

    <!-- 采购入库和人工入库物料表 - 采用stockIn.vue样式 -->
    <view
      class="material-table-section"
      v-if="
        (currentInType === 'purchase' || currentInType === 'manual') &&
        materialTable.length > 0
      "
    >
      <scroll-view
        class="table-scroll"
        scroll-y
        scroll-x
        @scroll="handleMaterialTableScroll"
        ref="materialTableScroll"
      >
        <!-- 滚动提示 -->
        <view
          class="scroll-hint"
          :class="{ show: showScrollHint }"
          v-if="showScrollHint"
        >
          <text class="hint-icon">→</text>
          <text>横向滑动查看更多信息</text>
        </view>
        <view class="table-row header">
          <text class="header-cell">选择</text>
          <text class="header-cell">物料名称</text>
          <text class="header-cell">净重(KG)</text>
          <text class="header-cell">数量</text>
          <text class="header-cell">物料编码</text>
          <text class="header-cell">合同编码</text>
          <text class="header-cell">操作</text>
        </view>
        <view
          v-for="(item, index) in materialTable"
          :key="item.id"
          class="table-row"
          :class="{
            selected: selectedMaterialRows.some((row) => row.id === item.id),
          }"
          @click="toggleMaterialSelection(item)"
        >
          <view class="table-cell">
            <view
              class="custom-checkbox"
              @click="toggleMaterialSelection(item)"
            >
              <view
                class="checkbox-icon"
                :class="{
                  'checkbox-checked': selectedMaterialRows.some(
                    (row) => row.id === item.id
                  ),
                }"
              >
                <text
                  v-if="selectedMaterialRows.some((row) => row.id === item.id)"
                  class="check-mark"
                  >✓</text
                >
              </view>
            </view>
          </view>
          <text class="table-cell">{{ item.materialName || "-" }}</text>
          <view class="table-cell quantity-cell">
            <input
              type="digit"
              v-model="item.prodCount"
              @input="validateNumber($event, item, 'prodCount')"
              class="quantity-input large-input"
              placeholder="请输入重量"
            />
          </view>
          <view class="table-cell quantity-cell">
            <input
              type="number"
              v-model="item.transCount"
              @input="validateNumber($event, item, 'transCount')"
              class="quantity-input large-input"
              placeholder="请输入数量"
            />
          </view>
          <text class="table-cell">{{ item.materialCode || "-" }}</text>
          <text class="table-cell">{{ item.poContractDetailCode || "-" }}</text>
          <view class="table-cell">
            <button
              class="btn-delete"
              @click="deleteMaterialRow(index)"
              size="mini"
              type="warn"
            >
              删除
            </button>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 统计信息 -->
    <view class="statistics-section">
      <view class="stat-item">
        <text class="stat-label">总数量</text>
        <text class="stat-value">{{ totalQuantity }}</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">总重量</text>
        <text class="stat-value">{{ totalWeight }} KG</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="button-row">
        <button class="btn-reset" @click="resetForm">重置</button>
        <button class="btn-submit" @click="submitForm">提交入库</button>
      </view>
    </view>
  </view>
</template>

<script>
import {
  queryWeighMid,
  queryPoContractDetail,
  queryMaterial,
  createCompletePoStockIn,
} from "@/api/warehouse/stockIn";
import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";
// 导入物料API
import { MaterialApi } from "@/api/md/material/index.js";
// 导入PDA扫码
import ScanInput from "@/components/ScanInput/ScanInput.vue";
// 导入数采计量工具
import { getDasKey } from "@/pages/smart/utils/das.js";

export default {
  name: "InWarehouseCreate",
  components: {
    ScanInput,
  },
  data() {
    return {
      // 入库类型配置
      inTypeOptions: [
        { value: "weigh", label: "检斤入库" },
        { value: "purchase", label: "采购入库" },
        { value: "manual", label: "人工入库" },
      ],
      inTypeIndex: 0,

      // 表单数据
      formData: {
        inType: "weigh",
        queryDate: dateHelperApi.formatDateTime(dateHelperApi.getCurrentDate()),
        warehouseId: "",
        warehouseName: "",
        isLoading: false,
      },

      // 时间筛选
      timeFilter: "today",

      // 搜索表单
      searchForm: {
        materialName: "",
        supplierId: "",
        supplierName: "",
        quantity: null, // 新增：数量输入
        materialCode: "", // 新增：物料编码输入
      },

      // 数量单位相关
      unitIndex: 0, // 默认选中第一个单位
      unitOptions: ["件", "个", "套", "台"], // 单位选项

      // 物料编码输入
      materialCode: "", // 新增：物料编码输入
      materialName: "", // 新增：物料名称输入

      // 数据列表
      supplierList: [],
      supplierIndex: -1,
      documentList: [],
      materialList: [],
      currentWarehouse: null,

      // 采购入库物料表格数据
      materialTable: [], // 新增：采购入库模式下的物料表格

      // Tab选项卡状态
      activeTab: "current", // 当前激活的tab: 'current' (当前数据) 或 'selected' (选中待入库)

      // 检斤数据专用
      weightTable: [], // 检斤记录列表
      selectedWeightRow: null, // 选中的检斤行
      selectedWeightRows: [], // 选中的检斤行列表（支持多选）
      weightTotalWeight: 0, // 选中检斤行的总净重
      weightTotalQuantity: 0, // 选中检斤行的总数量

      // 物料表选择功能
      selectedMaterialRows: [], // 选中的物料行列表（支持多选）

      // 字段显示控制
      hiddenFields: ["id", "supplier", "vehicleno"], // 不显示的字段列表

      // 时间筛选
      timeFilter: "today", // 默认选中当日
      contractTimeFilter: "today", // 合同查询区域时间筛选
      weighTimeFilter: "today", // 检斤查询区域时间筛选

      // 合同数据
      contractTable: [], // 合同列表
      selectedContract: null, // 选中的合同（单选模式）
      contractPageSize: 5, // 合同列表每页显示行数
      contractCurrentPage: 1, // 合同列表当前页码

      // 检斤数据分页
      weightPageSize: 5, // 检斤列表每页显示行数
      weightCurrentPage: 1, // 检斤列表当前页码

      // 显示控制
      showDocumentList: false,
      showWeightTable: false, // 显示检斤表格
      showContractTable: false, // 显示合同表格

      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 5,
        startDate: "", // 开始日期
        endDate: "", // 结束日期
      },

      // 加载状态
      isLoading: false,

      // 表格滚动提示
      showScrollHint: false,
      showWeightScrollHint: false,
      showContractScrollHint: false,
    };
  },

  computed: {
    // 暴露dateHelperApi供模板使用
    dateHelperApi() {
      return dateHelperApi;
    },

    currentInType() {
      return this.inTypeOptions[this.inTypeIndex]?.value;
    },

    searchSectionTitle() {
      const titles = {
        weigh: "检斤查询",
        purchase: "采购合同查询",
        manual: "信息确认",
      };
      return titles[this.currentInType] || "查询";
    },

    documentListTitle() {
      const titles = {
        weigh: "检斤记录",
        purchase: "采购合同",
        manual: "物料列表",
      };
      return titles[this.currentInType] || "列表";
    },

    totalQuantity() {
      // 检斤模式下，根据选中的检斤记录计算总数量
      if (this.currentInType === "weigh") {
        return this.selectedWeightRows.reduce(
          (sum, item) => sum + (Number(item.quantity) || 0),
          0
        );
      }
      // 采购和人工入库模式下，根据选中的物料行计算总数量
      if (
        this.currentInType === "purchase" ||
        this.currentInType === "manual"
      ) {
        return this.selectedMaterialRows.reduce(
          (sum, item) => sum + (Number(item.transCount) || 0),
          0
        );
      }
      // 其他模式下，根据物料列表计算
      return this.materialList.reduce(
        (sum, item) => sum + (Number(item.quantity) || 0),
        0
      );
    },

    totalWeight() {
      // 检斤模式下，根据选中的检斤记录计算总重量
      if (this.currentInType === "weigh") {
        return this.selectedWeightRows.reduce(
          (sum, item) => sum + (Number(item.netWeight) || 0),
          0
        );
      }
      // 采购和人工入库模式下，根据选中的物料行计算总重量
      if (
        this.currentInType === "purchase" ||
        this.currentInType === "manual"
      ) {
        return this.selectedMaterialRows.reduce(
          (sum, item) => sum + (Number(item.prodCount) || 0),
          0
        );
      }
      // 其他模式下，根据物料列表计算
      return this.materialList.reduce(
        (sum, item) => sum + (Number(item.weight) || 0),
        0
      );
    },
  },

  mounted() {
    // 初始化时间范围
    this.handleTimeChange("today");

    this.$nextTick(() => {
      this.loadInitialData();
    });

    // 初始化输入法状态
    this.initInputMethod();

    // 启动PDA扫码（如果设备支持）
    this.startPdaContinuousScan();
  },

  watch: {
    contractTable: {
      handler(newVal, oldVal) {
        console.log("contractTable发生变化:", {
          oldLength: oldVal ? oldVal.length : 0,
          newLength: newVal ? newVal.length : 0,
          newData: newVal,
        });
      },
      deep: true,
    },
    showContractTable: {
      handler(newVal, oldVal) {
        console.log("showContractTable发生变化:", {
          oldValue: oldVal,
          newValue: newVal,
        });
      },
    },
  },

  methods: {
    /**
     * 初始化输入法状态
     */
    initInputMethod() {
      // 从本地存储读取输入法状态
      const saved = uni.getStorageSync("inputMethodEnabled");
      if (saved !== null && saved !== undefined) {
        this.inputMethodEnabled = saved;
      }
    },

    /**
     * 加载更多合同数据
     */
    loadMoreContracts() {
      this.contractCurrentPage++;
    },

    /**
     * 加载更多检斤数据
     */
    loadMoreWeights() {
      this.weightCurrentPage++;
    },

    /**
     * 数字输入校验
     */
    validateNumber(event, item, field) {
      const value = event.target.value;

      // 如果是空字符串，直接设置为空
      if (value === "" || value === null || value === undefined) {
        item[field] = "";
        // 同步到统一计算的字段
        if (field === "prodCount") {
          item.weight = 0;
        } else if (field === "transCount") {
          item.quantity = 0;
        }
        return;
      }

      // 只允许数字和小数点
      const validValue = value.replace(/[^0-9.]/g, "");

      // 处理多个小数点的情况
      const parts = validValue.split(".");
      if (parts.length > 2) {
        item[field] = parts[0] + "." + parts.slice(1).join("");
      } else {
        item[field] = validValue;
      }

      // 同步到统一计算的字段
      if (field === "prodCount") {
        item.weight = Number(item.prodCount) || 0;
      } else if (field === "transCount") {
        item.quantity = Number(item.transCount) || 0;
      }
    },

    /**
     * 删除物料表行
     */
    deleteMaterialRow(index) {
      uni.showModal({
        title: "确认删除",
        content: "确定要删除这条物料记录吗？",
        success: (res) => {
          if (res.confirm) {
            const deletedItem = this.materialTable[index];
            // 从选中列表中移除
            const selectedIndex = this.selectedMaterialRows.findIndex(
              (row) => row.id === deletedItem.id
            );
            if (selectedIndex > -1) {
              this.selectedMaterialRows.splice(selectedIndex, 1);
            }
            this.materialTable.splice(index, 1);
            uni.showToast({
              title: "删除成功",
              icon: "success",
              duration: 1500,
            });
          }
        },
      });
    },

    /**
     * 切换物料行选择状态
     */
    toggleMaterialSelection(item) {
      const index = this.selectedMaterialRows.findIndex(
        (row) => row.id === item.id
      );
      if (index > -1) {
        this.selectedMaterialRows.splice(index, 1);
      } else {
        this.selectedMaterialRows.push(item);
      }
      // 更新统计信息
      this.updateMaterialStatistics();
    },

    /**
     * 切换检斤行选择状态
     */
    toggleWeightSelection(item) {
      const index = this.selectedWeightRows.findIndex(
        (row) => row.id === item.id
      );
      if (index > -1) {
        this.selectedWeightRows.splice(index, 1);
      } else {
        this.selectedWeightRows.push(item);
      }
      this.updateWeightStatistics();
    },

    /**
     * 更新检斤统计信息
     * 注意：这里使用普通属性而非计算属性，可以手动赋值
     */
    updateWeightStatistics() {
      this.weightTotalWeight = this.selectedWeightRows.reduce(
        (sum, item) => sum + (Number(item.netWeight) || 0),
        0
      );
      this.weightTotalQuantity = this.selectedWeightRows.reduce(
        (sum, item) => sum + (Number(item.quantity) || 0),
        0
      );
    },

    /**
     * 更新物料统计信息
     * 注意：totalWeight和totalQuantity是计算属性，会自动更新，无需手动赋值
     */
    updateMaterialStatistics() {
      // 计算属性会自动根据selectedMaterialRows的变化而更新
      // 这里可以添加其他需要手动更新的统计逻辑
      console.log("物料统计信息已更新");
    },

    /**
     * 处理合同表格滚动事件
     */
    handleTableScroll(event) {
      const scrollLeft = event.detail.scrollLeft;
      const scrollWidth = event.detail.scrollWidth;
      const clientWidth = event.detail.clientWidth;

      // 当可以横向滚动时显示提示
      if (scrollWidth > clientWidth) {
        // 滚动到最右边时隐藏提示
        if (scrollLeft >= scrollWidth - clientWidth - 10) {
          this.showContractScrollHint = false;
        } else {
          this.showContractScrollHint = true;
        }
      } else {
        this.showContractScrollHint = false;
      }
    },

    /**
     * 处理物料表格滚动事件
     */
    handleMaterialTableScroll(event) {
      const scrollLeft = event.detail.scrollLeft;
      const scrollWidth = event.detail.scrollWidth;
      const clientWidth = event.detail.clientWidth;

      // 当可以横向滚动时显示提示
      if (scrollWidth > clientWidth) {
        // 滚动到最右边时隐藏提示
        if (scrollLeft >= scrollWidth - clientWidth - 10) {
          this.showScrollHint = false;
        } else {
          this.showScrollHint = true;
        }
      } else {
        this.showScrollHint = false;
      }
    },

    /**
     * 处理检斤表格滚动事件
     */
    handleWeightTableScroll(event) {
      const scrollLeft = event.detail.scrollLeft;
      const scrollWidth = event.detail.scrollWidth;
      const clientWidth = event.detail.clientWidth;

      // 当可以横向滚动时显示提示
      if (scrollWidth > clientWidth) {
        // 滚动到最右边时隐藏提示
        if (scrollLeft >= scrollWidth - clientWidth - 10) {
          this.showWeightScrollHint = false;
        } else {
          this.showWeightScrollHint = true;
        }
      } else {
        this.showWeightScrollHint = false;
      }
    },

    /**
     * 启动PDA连续扫码
     * 在输入法关闭时启用PDA扫码，开启时使用输入法
     */
    startPdaContinuousScan() {
      // 只有在输入法关闭时才启用PDA扫码
      if (!this.inputMethodEnabled) {
        const success = this.startPdaScan((barcode) => {
          // 扫码结果处理
          this.handleMaterialScanResult(barcode);
        });

        if (success) {
          console.log("PDA连续扫码已启动");
        } else {
          console.warn("PDA扫码启动失败，将使用手动输入模式");
        }
      }
    },

    /**
     * 处理物料扫码结果
     * @param {string} barcode - 扫码得到的条码内容
     */
    async handleMaterialScanResult(barcode) {
      if (!barcode) return;
      this.isLoading = true;
      console.log("PDA物料扫码结果:", barcode);

      // 如果扫码内容以DAS开头，则调用数采计量方法
      if (barcode.startsWith("DAS")) {
        await this.handleMeasureWeight(barcode);
        this.isLoading = false;
        return;
      }
      console.log("barcodeDAS:", barcode);
      this.materialTable = [];
      // 将扫码结果赋值给搜索框
      this.searchForm.materialCode = barcode;

      // 人工入库模式下，扫码获取物料编码后查询主数据
      if (this.currentInType === "manual") {
        try {
          await this.searchMaterialByCode();
        } catch (error) {
          console.error("查询物料主数据失败:", error);
          uni.showToast({
            title: "查询失败，请重试",
            icon: "none",
            duration: 2000,
          });
        } finally {
          this.isLoading = false;
        }
      } else {
        // 其他模式下执行原有逻辑
        this.matchContract();
        this.isLoading = false;
      }
    },

    /**
     * 数采计量方法
     * 当扫码内容以DAS开头时调用，获取计量数据并赋值到物料列表
     */
    async handleMeasureWeight(parameterName) {
      try {
        // 显示加载提示
        uni.showLoading({
          title: "计量中...",
        });

        // 调用getDasKey方法获取计量数据
        const result = await getDasKey(parameterName);
        console.log("数采result.result[0].v:", result.result[0].v);
        uni.hideLoading();

        // 处理返回的数据
        let weightValue = null;
        if (result) {
          weightValue = result.result[0].v || 0;
        }

        if (weightValue !== null && weightValue !== undefined) {
          const parsedValue = parseFloat(weightValue);
          if (!isNaN(parsedValue)) {
            // 判断物料列表是否有数据
            if (this.materialTable && this.materialTable.length > 0) {
              // 将计量值赋值到第一行的净重KG列
              this.materialTable[0].prodCount = parsedValue;
              uni.showToast({
                title: `计量成功：${parsedValue}KG`,
                icon: "success",
              });
            } else {
              uni.showToast({
                title: "当前没有可赋值的物料数据",
                icon: "none",
              });
            }
          } else {
            uni.showToast({
              title: "获取到的计量数据格式不正确",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: "未找到对应的数采配置或数据为空",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error("计量失败:", error);
        uni.showToast({
          title: error.message || "计量失败，请检查数采配置",
          icon: "none",
        });
      }
    },

    // 聚焦到输入框（输入法开启时弹出键盘）
    focusMaterialInput() {
      if (this.inputMethodEnabled && this.$refs.materialInput) {
        this.$nextTick(() => {
          if (this.$refs.materialInput.focus) {
            this.$refs.materialInput.focus();
          }
        });
      }
    },

    /**
     * 输入法开关切换处理
     */
    handleInputMethodSwitchChange() {
      this.inputMethodEnabled = !this.inputMethodEnabled;

      // 保存到本地存储
      uni.setStorageSync("inputMethodEnabled", this.inputMethodEnabled);

      // 如果开启输入法，聚焦输入框
      if (this.inputMethodEnabled) {
        this.focusMaterialInput();
        // 停止PDA扫码
        this.stopPdaScan();
      } else {
        // 如果关闭输入法，启动PDA扫码
        this.startPdaContinuousScan();
      }
    },

    // 时间筛选器变更处理（合同查询区域）
    handleContractTimeChange(filter) {
      this.contractTimeFilter = filter;
      dateHelperApi.updateDateRange(filter, {
        callback: ({ startDate, endDate }) => {
          this.queryParams.startDate = startDate;
          this.queryParams.endDate = endDate;
          console.log("currentInType:", this.currentInType);
          this.searchForm.materialName = "";
          // 合同查询
          if (
            this.currentInType === "purchase" ||
            this.currentInType === "weigh"
          ) {
            this.matchContract();
          }
        },
      });
    },

    // 时间筛选器变更处理（检斤查询区域）
    handleWeighTimeChange(filter) {
      this.weighTimeFilter = filter;
      dateHelperApi.updateDateRange(filter, {
        callback: ({ startDate, endDate }) => {
          this.queryParams.startDate = startDate;
          this.queryParams.endDate = endDate;
          console.log("检斤查询时间范围:", {
            startDate,
            endDate,
          });
          // 检斤查询
          if (this.currentInType === "weigh" && this.searchForm.materialName) {
            this.searchWeighData();
          }
        },
      });
    },

    // 时间筛选器变更处理（兼容旧版本）
    handleTimeChange(filter) {
      this.timeFilter = filter;
      dateHelperApi.updateDateRange(filter, {
        callback: ({ startDate, endDate }) => {
          this.queryParams.startDate = startDate;
          this.queryParams.endDate = endDate;
          console.log("时间筛选（兼容模式）:", {
            startDate,
            endDate,
          });
          // 根据当前入库类型执行相应的查询
          if (this.currentInType === "weigh" && this.searchForm.materialName) {
            this.searchWeighData();
          } else if (
            this.currentInType === "purchase" &&
            this.searchForm.materialName
          ) {
            this.matchContract();
          }
        },
      });
    },

    // 获取当前日期
    getCurrentDate() {
      return dateHelperApi.getCurrentDateTime();
    },

    // 加载初始数据
    async loadInitialData() {
      try {
        const warehouseRes = await this.getCurrentWarehouse();
        if (warehouseRes) {
          this.currentWarehouse = warehouseRes;
          this.formData.warehouseId = warehouseRes.warehouseId;
          this.formData.warehouseName = warehouseRes.warehouseName;
        }

        // 重新加载数据
        this.$nextTick(() => {
          this.matchContract();
        });
      } catch (error) {
        console.error("加载初始数据失败:", error);
      }
    },

    // 获取当前用户仓库
    async getCurrentWarehouse() {
      try {
        // 从Vuex store获取用户配置的仓库信息
        const userConfig = this.$store.state.user.userConfig;
        if (userConfig && userConfig.wmName) {
          return {
            warehouseId: userConfig.warehouseId || "DEFAULT",
            warehouseName: userConfig.wmName,
          };
        }

        // 降级处理：尝试其他字段
        if (userConfig && userConfig.warehouseName) {
          return {
            warehouseId: userConfig.warehouseId || "DEFAULT",
            warehouseName: userConfig.warehouseName,
          };
        }
      } catch (error) {
        console.error("获取用户仓库失败:", error);
      }
    },

    // 切换入库类型（标签页方式）
    switchInType(type) {
      // 检查是否有未入库的数据
      if (this.materialList.length > 0) {
        uni.showModal({
          title: "提示",
          content: "有数据未入库，请先提交入库或删除待入库数据",
          confirmText: "去提交",
          cancelText: "删除数据",
          success: (res) => {
            if (res.confirm) {
              // 用户选择去提交，不做任何操作
              return;
            } else if (res.cancel) {
              // 用户选择删除数据，清空materialList
              this.materialList = [];
              // 同时清除原表格中的选中状态
              this.clearOriginalTableSelection();
              // 继续切换入库类型
              this.continueInTypeChange(type);
            }
          },
        });
      } else {
        // 没有数据，直接切换
        this.continueInTypeChange(type);
      }
    },

    // 继续入库类型变更
    continueInTypeChange(type) {
      // 根据类型设置对应的索引
      const typeIndex = this.inTypeOptions.findIndex(
        (item) => item.value === type
      );
      if (typeIndex !== -1) {
        this.inTypeIndex = typeIndex;
        this.formData.inType = type;
      }

      // 重置搜索条件
      this.resetSearch();

      // 重置所有查询结果表
      this.resetQueryResults();
    },

    // 清除原表格中的选中状态
    clearOriginalTableSelection() {
      this.materialTable.forEach((item) => {
        if (item.isCheck) {
          this.$set(item, "isCheck", false);
          this.$set(item, "showError", false);
          this.$set(item, "prod_count", 0);
          this.$set(item, "trans_count", 0);
        }
      });
    },

    // 处理返回按钮点击
    handleBack() {
      // 检查是否有未入库的数据
      if (this.materialList.length > 0) {
        uni.showModal({
          title: "提示",
          content: "有数据未入库，请先提交入库或删除待入库数据",
          confirmText: "去提交",
          cancelText: "删除数据",
          success: (res) => {
            if (res.confirm) {
              // 用户选择去提交，不做任何操作
              return;
            } else if (res.cancel) {
              // 用户选择删除数据，清空materialList
              this.materialList = [];
              // 同时清除原表格中的选中状态
              this.clearOriginalTableSelection();
              // 返回上一页
              uni.navigateBack();
            }
          },
        });
      } else {
        // 没有数据，直接返回
        uni.navigateBack();
      }
    },

    // 重置所有查询结果表
    resetQueryResults() {
      // 重置合同表
      this.contractTable = [];
      this.showContractTable = false;

      // 重置检斤表
      this.weightTable = [];
      this.showWeightTable = false;
      this.selectedWeightRow = null;

      // 重置物料表
      this.materialTable = [];

      // 重置物料编码和名称输入
      this.materialCode = "";
      this.materialName = "";

      // 重置时间筛选 - 保持各自区域的独立性
      this.contractTimeFilter = "today";
      this.weighTimeFilter = "today";
      this.timeFilter = "today";
    },

    // 日期变更
    handleDateChange(e) {
      this.formData.queryDate = e.detail.value;
    },

    // 时间选择处理
    handleTimeChange(timeFilter) {
      // 更新时间筛选器
      this.timeFilter = timeFilter;

      // 使用通用的updateDateRange函数
      const result = dateHelperApi.updateDateRange(timeFilter, {
        callback: ({ startDate, endDate }) => {
          // 更新时间范围
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
        },
      });

      // 重新加载数据
      this.$nextTick(() => {
        this.loadInitialData();
      });
    },

    // 供应商变更
    handleSupplierChange(e) {
      this.supplierIndex = e.detail.value;
      const selectedSupplier = this.supplierList[this.supplierIndex];
      if (selectedSupplier) {
        this.searchForm.supplierId = selectedSupplier.supplierId;
        this.searchForm.supplierName = selectedSupplier.supplierName;
      }
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        materialName: "",
        supplierId: "",
        supplierName: "",
        quantity: null, // 重置数量
        materialCode: "", // 重置物料编码
      };
      this.unitIndex = 0; // 重置单位选择
      this.supplierIndex = -1;
      this.documentList = [];
      this.showDocumentList = false;
      this.selectedWeightRows = []; // 清空多选列表

      // 重置各自区域的时间筛选
      this.contractTimeFilter = "today";
      this.weighTimeFilter = "today";
    },

    // 验证搜索数量输入
    validateSearchQuantity() {
      if (
        this.searchForm.quantity !== null &&
        this.searchForm.quantity !== undefined
      ) {
        // 确保数量为有效数字且大于0
        const quantity = Number(this.searchForm.quantity);
        if (isNaN(quantity) || quantity <= 0) {
          uni.showToast({
            title: "请输入有效的数量（大于0）",
            icon: "none",
          });
          this.searchForm.quantity = null;
        } else if (quantity > 999999) {
          uni.showToast({
            title: "数量超出范围（最大999999）",
            icon: "none",
          });
          this.searchForm.quantity = 999999;
        }
      }
    },

    // 处理单位选择变化
    handleUnitChange(e) {
      this.unitIndex = e.detail.value;
    },

    // 获取单位索引
    getUnitIndex(unit) {
      return this.unitOptions.indexOf(unit) !== -1
        ? this.unitOptions.indexOf(unit)
        : 0;
    },

    // 处理检斤行的单位选择变化
    handleWeightUnitChange(e, item) {
      const selectedUnit = this.unitOptions[e.detail.value];
      this.$set(item, "unit", selectedUnit);
    },

    // 验证检斤行数量输入
    validateWeightQuantity(event, item) {
      const value = Number(event.target.value);
      if (isNaN(value) || value < 0) {
        uni.showToast({
          title: "请输入有效的数量（不小于0）",
          icon: "none",
        });
        item.quantity = 0;
      } else if (value > 999999) {
        uni.showToast({
          title: "数量超出范围（最大999999）",
          icon: "none",
        });
        item.quantity = 999999;
      }
    },

    // 处理检斤行数量输入变化（实时更新汇总）
    handleWeightQuantityInput(item) {
      // 确保数量值为有效数字
      if (
        item.quantity === "" ||
        item.quantity === null ||
        item.quantity === undefined
      ) {
        item.quantity = 0;
      } else {
        item.quantity = Number(item.quantity) || 0;
      }

      // 输入数量后，取消当前行的选中状态
      if (item.quantity > 0) {
        const index = this.weightTable.indexOf(item);
        if (index !== -1) {
          // 取消当前行的选中状态
          const existingIndex = this.selectedWeightRows.findIndex(
            (selected) => selected.index === index
          );
          if (existingIndex !== -1) {
            this.selectedWeightRows.splice(existingIndex, 1);
          }
          // 更新当前选中行
          if (this.selectedWeightRow === item) {
            this.selectedWeightRow = null;
          }
        }
      }

      // 实时更新汇总统计信息
      this.updateWeightStatistics();
    },

    // 检斤数据查询
    async searchWeighData() {
      try {
        uni.showLoading({ title: "查询中..." });

        // 验证数量输入
        if (
          this.searchForm.quantity !== null &&
          this.searchForm.quantity !== undefined
        ) {
          const quantity = Number(this.searchForm.quantity);
          if (isNaN(quantity) || quantity <= 0) {
            uni.showToast({
              title: "请输入有效的数量（大于0）",
              icon: "none",
            });
            uni.hideLoading();
            return;
          }
        }

        // 获取时间范围
        const dateRange = this.getQueryDateRange();

        // 构建参数 - 使用时间戳数组格式（后端期望数字时间戳）
        const params = {
          pageNum: this.queryParams.pageNo,
          pageSize: this.queryParams.pageSize,
          materialName: this.searchForm.materialName || undefined, // 物料名称筛选
          quantity: this.searchForm.quantity || undefined, // 数量筛选
          unit: this.unitOptions[this.unitIndex] || undefined, // 单位筛选
          reader: "", //查询未读取的数据
        };

        // 只有在时间范围有效时才添加时间参数
        if (dateRange.startDate && dateRange.endDate) {
          // dateHelperApi.updateDateRange返回的是YYYY-MM-DD HH:mm:ss格式
          // 使用数组格式传递时间范围，与stockIn.vue等其他页面保持一致
          params.createTime = [dateRange.startDate, dateRange.endDate];
        }
        // 调用检斤查询API
        const res = await queryWeighMid(params);

        if (res.code === 0) {
          this.weightTable = (res.data?.list || []).map((item) => ({
            ...item,
            quantity: item.quantity || item.transCount || 0, // 初始化数量字段，优先使用quantity，其次使用transCount，默认为0
          }));
          this.showWeightTable = true;

          uni.showToast({
            title: `查询到${this.weightTable.length}条记录`,
            icon: "success",
          });
        } else {
          uni.showToast({ title: res.msg || "查询失败", icon: "none" });
        }
      } catch (error) {
        console.error("检斤查询失败:", error);
        uni.showToast({ title: "查询失败，请重试", icon: "none" });
      } finally {
        uni.hideLoading();
      }
    },

    // 选中检斤行 - 支持多选（以index为选中行依据）
    selectWeightRow(row, index) {
      // 查找是否已选中该行
      const existingIndex = this.selectedWeightRows.findIndex(
        (item) => item.index === index
      );

      if (existingIndex !== -1) {
        // 如果已选中，则取消选中
        this.selectedWeightRows.splice(existingIndex, 1);
      } else {
        // 否则添加到选中列表，包含index信息
        this.selectedWeightRows.push({ ...row, index });
      }

      // 更新当前选中行（用于显示）
      this.selectedWeightRow = existingIndex !== -1 ? null : row;

      // 实时汇总选中行的净重和数量到统计信息
      this.updateWeightStatistics();

      // 如果用户输入了数量，则使用用户输入的数量
      // 如果用户选择了单位，则使用用户选择的单位
      if (this.searchForm.quantity && this.searchForm.quantity > 0) {
        // 使用用户输入的数量
      } else if (row && this.materialList.length > 0 && existingIndex === -1) {
        // 自动将选中行的净重赋值到物料明细的重量字段（只在新增选中时）
        this.materialList.forEach((item) => {
          if (!item.weight || item.weight === 0) {
            item.weight = row.actualwt || 0;
          }
        });
      }

      // 如果用户选择了单位，更新物料的单位
      if (this.unitOptions[this.unitIndex] && this.materialList.length > 0) {
        this.materialList.forEach((item) => {
          item.unit = this.unitOptions[this.unitIndex];
        });
      }
    },

    // 更新检斤统计信息
    updateWeightStatistics() {
      // 计算选中检斤行的总净重和总数量
      const totalWeight = this.selectedWeightRows.reduce(
        (sum, item) => sum + (Number(item.actualwt) || 0),
        0
      );
      const totalQuantity = this.selectedWeightRows.reduce(
        (sum, item) => sum + (Number(item.quantity) || 0),
        0
      );

      // 更新统计信息（转换为显示单位）
      this.weightTotalWeight = totalWeight;
      this.weightTotalQuantity = totalQuantity;

      console.log("检斤统计信息更新:", {
        selectedRows: this.selectedWeightRows.length,
        totalWeight: totalWeight,
        totalQuantity: totalQuantity,
      });
    },

    // 搜索物料（保留原有方法用于其他入库类型）
    async searchMaterials() {
      try {
        let res;
        if (this.currentInType === "weigh") {
          // 检斤入库现在使用专门的searchWeighData方法
          return;
        } else {
          res = await queryMaterial({
            materialCode: this.materialCode,
            materialName: this.materialName,
            pageNum: 1,
            pageSize: 20,
          });
        }
        if (res.code === 0) {
          // 根据入库类型决定数据存储位置
          if (
            this.currentInType === "purchase" ||
            this.currentInType === "manual"
          ) {
            // 采购入库：直接显示在物料表格中，确保重量和数量默认为0
            // 保留已确认的物料状态，新搜索的物料展现在未确认物料中
            const newMaterials = (res.data?.list || []).map((item) => {
              // 检查该物料是否已经在materialTable中存在且已确认
              const existingItem = this.materialTable.find(
                (tableItem) =>
                  tableItem.materialCode === item.materialCode &&
                  tableItem.isCheck
              );

              if (existingItem) {
                // 如果已存在且已确认，保持其状态
                return existingItem;
              } else {
                // 新物料或未确认的物料
                return {
                  ...item,
                  prod_count: "", // 重量默认为空
                  trans_count: "", // 数量默认为空
                  isCheck: false, // 确认状态默认为false
                  showError: false, // 错误状态默认为false
                };
              }
            });

            this.materialTable = newMaterials;
          }
        }
      } catch (error) {
        console.error("搜索物料失败:", error);
      }
    },

    // 人工入库模式下通过物料编码查询物料（使用MaterialApi.getMaterialPage）
    async searchMaterialByCode() {
      if (!this.searchForm.materialCode) {
        uni.showToast({
          title: "请输入物料编码",
          icon: "none",
          duration: 2000,
        });
        return;
      }

      try {
        this.isLoading = true;

        // 使用MaterialApi.getMaterialByCode
        const params = {
          materialCode: this.searchForm.materialCode,
        };

        const response = await MaterialApi.getMaterialByCode(params);

        if (response.code === 0 && response.data) {
          // 清空现有物料表
          this.materialTable = [];

          // 处理返回的物料数据（单个对象）
          const materialData = response.data;
          const materialRow = {
            id: Date.now(), // 为物料生成唯一ID
            materialName: materialData.materialName || "未知物料",
            materialCode:
              materialData.materialCode || this.searchForm.materialCode,
            prodCount: "", // 净重，初始为空，用户可编辑
            transCount: "", // 数量，初始为空，用户可编辑
            weight: 0, // 重量字段，用于统一计算
            quantity: 0, // 数量字段，用于统一计算
          };

          this.materialTable = [materialRow];

          uni.showToast({
            title: "已获取物料信息",
            icon: "success",
            duration: 1500,
          });
        } else {
          // 如果查询不到数据，创建基础物料行
          const materialRow = {
            id: Date.now(),
            materialName: "未知物料",
            materialCode: this.searchForm.materialCode,
            prodCount: "",
            transCount: "",
            weight: 0,
            quantity: 0,
          };

          this.materialTable = [materialRow];

          uni.showToast({
            title: "未找到物料主数据",
            icon: "none",
            duration: 2000,
          });
        }
      } catch (error) {
        console.error("查询物料失败:", error);
        uni.showToast({
          title: "查询失败，请重试",
          icon: "none",
          duration: 2000,
        });
      } finally {
        this.isLoading = false;
      }
    },

    // 选择单据/合同
    selectDocument(item) {
      // 根据选择的单据加载物料明细
      if (this.currentInType === "purchase") {
        this.loadContractMaterials(item);
      } else {
        this.addMaterialToList(item);
      }
      this.showDocumentList = false;
    },

    // 加载合同物料
    async loadContractMaterials(contract) {
      try {
        // 这里应该调用合同明细接口
        // 临时使用示例数据
        const materials = [
          {
            materialCode: "MAT001",
            materialName: "钢材A",
            quantity: 100,
            unit: "吨",
            weight: 100000,
          },
        ];
        this.materialList = [...this.materialList, ...materials];
      } catch (error) {
        console.error("加载合同物料失败:", error);
      }
    },

    // 添加物料到列表
    addMaterialToList(material) {
      const exists = this.materialList.find(
        (item) => item.materialCode === material.materialCode
      );
      if (!exists) {
        this.materialList.push({
          materialCode: material.materialCode,
          materialName: material.materialName,
          quantity: 0,
          weight: 0,
          unit: material.unit || "件",
        });
      }
    },

    // 从物料表格添加到主物料列表，待保存专用
    addToMaterialList(item) {
      // 检查重量或数量是否有不为空或不为0的值
      const weight = Number(item.prod_count || 0);
      const quantity = Number(item.trans_count || 0);

      // 如果重量和数量都为空或0，标记为错误状态并提示
      if (weight === 0 && quantity === 0) {
        this.$set(item, "showError", true);
        uni.showToast({
          title: "重量和数量不能同时为空或0",
          icon: "none",
          duration: 2000,
        });
        return;
      }

      // 清除错误状态
      this.$set(item, "showError", false);

      // 标记该行为已确认（浅绿色）
      this.$set(item, "isCheck", true);

      // 创建要添加的物料对象
      const material = {
        materialCode: item.materialCode,
        materialName: item.materialName,
        quantity: quantity,
        weight: weight,
        unit: item.unit || "件",
        spec: item.spec || "", // 保留规格信息
        brand: item.brand || "", // 保留品牌信息
        isFromTable: true, // 标记为从表格添加的物料
        originalIndex: this.materialTable.indexOf(item), // 记录原始索引
      };

      // 查找是否已存在相同物料编码的物料
      const existingIndex = this.materialList.findIndex(
        (m) => m.materialCode === material.materialCode
      );

      if (existingIndex !== -1) {
        // 如果已存在，更新现有物料的重量和数量
        this.$set(this.materialList, existingIndex, {
          ...this.materialList[existingIndex],
          weight: weight,
          quantity: quantity,
          spec: item.spec || this.materialList[existingIndex].spec || "",
          brand: item.brand || this.materialList[existingIndex].brand || "",
          isFromTable: true,
          originalIndex: this.materialTable.indexOf(item),
        });
      } else {
        // 如果是新物料，添加到列表中
        // 查找最后一个从表格添加的物料位置
        let insertIndex = this.materialList.length;
        for (let i = this.materialList.length - 1; i >= 0; i--) {
          if (this.materialList[i].isFromTable) {
            insertIndex = i + 1;
            break;
          }
        }

        // 在适当位置插入新物料
        this.materialList.splice(insertIndex, 0, material);
      }

      // 显示成功提示
      uni.showToast({
        title: "物料已添加到待入库列表",
        icon: "success",
        duration: 1500,
      });
    },

    // 添加物料
    addMaterial() {
      if (this.currentInType === "purchase" && this.materialList.length === 0) {
        uni.showModal({
          title: "提示",
          content: "没有入库申请单据，确认人工入库操作？",
          success: (res) => {
            if (res.confirm) {
              this.showMaterialSelector();
            }
          },
        });
      } else {
        this.showMaterialSelector();
      }
    },

    // 显示物料选择器
    showMaterialSelector() {
      // 这里应该弹出物料选择器
      // 临时添加一个示例物料
      this.materialList.push({
        materialCode: "MAT" + Date.now(),
        materialName: "新物料",
        quantity: 0,
        weight: 0,
        unit: "件",
      });
    },

    // 移除物料
    removeMaterial(index) {
      this.materialList.splice(index, 1);
    },

    // 移除选中的待入库物料
    removeSelectedMaterial(item, index) {
      // 显示确认对话框
      uni.showModal({
        title: "确认移除",
        content: `确定要移除物料 "${item.materialName}" 吗？`,
        confirmText: "确定",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            // 用户确认移除
            this.performRemoveMaterial(item);
          }
        },
      });
    },

    // 执行移除物料操作
    performRemoveMaterial(item) {
      // 找到要移除的物料在materialList中的索引
      const index = this.materialList.findIndex(
        (m) =>
          m.materialCode === item.materialCode &&
          m.materialName === item.materialName
      );

      if (index > -1) {
        // 从materialList中移除物料
        this.materialList.splice(index, 1);

        // 如果该物料是从materialTable添加的，需要清除原表格中的选中状态
        if (item.isFromTable && item.originalIndex !== undefined) {
          const originalItem = this.materialTable[item.originalIndex];
          if (originalItem && originalItem.materialCode === item.materialCode) {
            // 清除原表格项的选中状态
            this.$set(originalItem, "isCheck", false);
            this.$set(originalItem, "showError", false);
            // 清空输入框的值
            this.$set(originalItem, "prod_count", "");
            this.$set(originalItem, "trans_count", "");
          }
        }

        uni.showToast({
          title: "已移除待入库物料",
          icon: "success",
          duration: 1500,
        });
      } else {
        uni.showToast({
          title: "移除失败：未找到物料",
          icon: "none",
          duration: 1500,
        });
      }
    },

    // 数字输入校验
    validateNumber(event, item, field) {
      const value = event.detail.value;
      // 只允许正数和最多2位小数
      const reg = /^\d*\.?\d{0,2}$/;
      if (!reg.test(value)) {
        // 非法输入，恢复原值
        this.$nextTick(() => {
          item[field] = this.formatNumberValue(item[field]);
        });
      }
      // 输入变化时更新统计信息
      this.updateMaterialStatistics();
    },

    // 数字格式化（保留2位小数）
    formatNumber(item, field) {
      const value = item[field];
      // 如果是空值，返回空字符串
      if (value === "" || value === null || value === undefined) {
        item[field] = "";
        return;
      }
      const num = Number(value);
      if (!isNaN(num) && num >= 0) {
        item[field] = num.toFixed(2);
      } else {
        item[field] = "0.00";
      }
    },

    // 格式化数字值
    formatNumberValue(value) {
      // 如果是空值，返回空字符串
      if (value === "" || value === null || value === undefined) {
        return "";
      }
      const num = Number(value);
      if (!isNaN(num) && num >= 0) {
        return num.toFixed(2);
      }
      return "0.00";
    },

    // 设置查询时间范围
    setQueryDateRange(startDate, endDate) {
      this.queryParams.startDate = startDate;
      this.queryParams.endDate = endDate;
      this.formData.queryDate = startDate;
    },

    // 获取查询时间范围
    getQueryDateRange() {
      if (this.queryParams.startDate && this.queryParams.endDate) {
        return {
          startDate: this.queryParams.startDate,
          endDate: this.queryParams.endDate,
        };
      }
      // 如果没有设置时间范围，使用当前表单日期
      return {
        startDate: this.formData.queryDate,
        endDate: this.formData.queryDate,
      };
    },

    // 匹配合同
    async matchContract() {
      try {
        // 获取时间范围
        const dateRange = this.getQueryDateRange();

        // 构建参数 - 使用分开的日期参数和更多筛选条件
        const params = {
          pageNum: this.queryParams.pageNo,
          pageSize: this.queryParams.pageSize,
          materialCode: this.searchForm.materialCode || undefined, // 物料编码筛选
          materialName: this.searchForm.materialName || undefined, // 物料名称筛选
          supplierId: this.searchForm.supplierId || undefined, // 供应商筛选
        };
        // 只有在时间范围有效时才添加时间参数
        if (dateRange.startDate && dateRange.endDate) {
          // dateHelperApi.updateDateRange返回的是YYYY-MM-DD HH:mm:ss格式
          // 使用数组格式传递时间范围，与stockIn.vue等其他页面保持一致
          params.createTime = [dateRange.startDate, dateRange.endDate];
        }
        console.log("匹配合同参数:", params);
        // 调用API查询采购合同
        const res = await queryPoContractDetail(params);
        if (res.code == 0) {
          this.contractTable = res.data.list || [];
          this.showContractTable = true;

          if (this.contractTable.length === 0) {
            uni.showToast({
              title: "未找到匹配的采购合同",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: res.msg || "查询合同失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("匹配合同失败:", error);
        uni.showToast({
          title: "匹配合同失败",
          icon: "none",
        });
      }
    },

    // 选择合同 - 单选功能，选中行背景显示浅绿色
    selectContract(contract) {
      this.selectedContract = contract;

      // 将选中行的materialName赋值给searchForm.materialName
      if (contract && contract.materialName) {
        this.searchForm.materialName = contract.materialName;
      }

      //采购入库模式下，将合同数据写入materialTable表
      if (this.currentInType === "purchase" && contract) {
        // 清空现有物料表和选中状态
        this.materialTable = [];
        this.selectedMaterialRows = [];

        // 创建新的物料行，复制选中合同的信息
        const materialRow = {
          id: Date.now(), // 生成唯一ID
          materialName: contract.materialName || "",
          prodCount: "", // 净重，初始为空，用户可编辑
          transCount: "", // 数量，初始为空，用户可编辑
          materialCode: contract.materialCode || "",
          poContractDetailCode: contract.poContractDetailCode || "",
          spec: contract.spec || "",
          weight: 0, // 重量字段，用于统一计算
          quantity: 0, // 数量字段，用于统一计算
        };

        this.materialTable = [materialRow];
        console.log("采购合同数据写入materialTable表:", materialRow);
      } else {
        // 调用查询检斤单方法
        this.searchWeighData();
      }
    },

    // 重置表单
    resetForm() {
      this.formData.queryDate = dateHelperApi.getCurrentDate();
      this.materialList = [];
      this.materialTable = [];
      this.resetSearch();
      this.weightTable = [];
      this.selectedWeightRow = null;
      this.selectedWeightRows = []; // 清空多选列表
      this.weightTotalWeight = 0; // 清空称重统计信息
      this.weightTotalQuantity = 0; // 清空称重统计信息
      this.selectedMaterialRows = []; // 清空物料选择列表
      this.showWeightTable = false;
      this.contractTable = [];
      this.selectedContract = null;
      this.showContractTable = false;
      // 重置分页
      this.contractCurrentPage = 1;
      this.weightCurrentPage = 1;
      // 重置时间筛选
      this.timeFilter = "today";
      this.contractTimeFilter = "today";
      this.weighTimeFilter = "today";
    },

    // 检斤模式提交验证
    async validateWeighSubmit() {
      console.log(
        "【检斤模式提交验证】",
        this.selectedWeightRows,
        this.selectedContract
      );
      // 检查是否选中了检斤记录
      const hasWeightSelected = this.selectedWeightRows.length > 0;

      // 检查是否选中了合同记录
      const hasContractSelected = this.selectedContract !== null;

      // 如果contractTable没有选中行信息，weightTable没有选中行信息，则进行相应提示
      if (!hasWeightSelected && !hasContractSelected) {
        return {
          valid: false,
          message: "请先选择检斤记录和采购合同",
        };
      }

      // 如果只有检斤记录没有选中合同
      if (hasWeightSelected && !hasContractSelected) {
        return {
          valid: false,
          message: "请先选择采购合同",
        };
      }

      // 如果只有合同没有选中检斤记录
      if (!hasWeightSelected && hasContractSelected) {
        return {
          valid: false,
          message: "请先选择检斤记录",
        };
      }

      // 如果都选中了，判断contractTable的物料名称是否相同
      if (hasWeightSelected && hasContractSelected) {
        // 获取选中合同的物料名称
        const contractMaterialName = this.selectedContract.materialName;

        // 获取选中检斤记录的物料名称列表
        const weightMaterialNames = this.selectedWeightRows
          .map((item) => item.product)
          .filter((name) => name);

        // 检查检斤记录的物料名称是否与合同一致
        const hasDifferentMaterial = weightMaterialNames.some(
          (name) => name !== contractMaterialName
        );

        if (hasDifferentMaterial) {
          // 显示确认对话框
          return new Promise((resolve) => {
            uni.showModal({
              title: "物料名称不一致",
              content: "采购合同和检斤单物料名称不同，确认是否入库？",
              confirmText: "确认入库",
              cancelText: "取消",
              success: (res) => {
                resolve({
                  valid: res.confirm,
                  message: res.confirm ? "" : "已取消入库操作",
                });
              },
            });
          });
        }
      }

      return { valid: true };
    },

    // 提交表单
    async submitForm() {
      console.log("【提交表单】", this.formData);
      // 显示加载状态
      uni.showLoading({
        title: "正在提交...",
        mask: true,
      });

      try {
        // 增强验证：必填字段检查
        const validation = this.validateForm();
        if (!validation.valid) {
          uni.hideLoading();
          uni.showToast({
            title: validation.message,
            icon: "none",
            duration: 2000,
          });
          return;
        }

        // 检斤模式下的特殊验证
        if (this.currentInType === "weigh") {
          const weighValidation = await this.validateWeighSubmit();
          if (!weighValidation.valid) {
            uni.hideLoading();
            uni.showToast({
              title: weighValidation.message,
              icon: "none",
              duration: 3000,
            });
            return;
          }
        }

        // 构建提交数据（根据新API格式）
        const submitData = this.buildNewSubmitData();

        // 提交前确认
        const confirmRes = await this.showSubmitConfirm(submitData);
        if (!confirmRes) {
          uni.hideLoading();
          return;
        }

        // 使用新API创建完整入库单
        console.log("submitData", submitData);
        const orderRes = await createCompletePoStockIn(submitData);
        //打印返回数据
        console.log("createCompletePoStockIn res", orderRes);
        if (orderRes.code === 0) {
          await this.handleSubmitSuccess(orderRes);
        } else {
          throw new Error(orderRes.msg || "创建入库单失败");
        }
      } catch (error) {
        await this.handleSubmitException(error);
      } finally {
        uni.hideLoading();
      }
    },

    // 表单验证
    validateForm() {
      if (!this.formData.warehouseName) {
        return { valid: false, message: "请选择仓库" };
      }

      if (!this.formData.queryDate) {
        return { valid: false, message: "请选择入库日期" };
      }
      if (this.currentInType === "weigh") {
        if (this.selectedWeightRows.length === 0) {
          return { valid: false, message: "请选择检斤记录" };
        }
        if (!this.selectedContract) {
          return { valid: false, message: "请选择采购合同" };
        }
      } else {
        if (this.selectedMaterialRows.length === 0) {
          return { valid: false, message: "请选择物料明细" };
        }
        // 验证物料明细
        for (let i = 0; i < this.selectedMaterialRows.length; i++) {
          const item = this.selectedMaterialRows[i];

          if (!item.materialName || item.materialName.trim() === "") {
            return { valid: false, message: `第${i + 1}条物料名称不能为空` };
          }

          const prodCountValue = item.prodCount || 0;
          if (!this.isValidNumber(prodCountValue) || prodCountValue < 0) {
            return { valid: false, message: `第${i + 1}条物料重量必须大于0` };
          }

          const transCountValue = item.transCount || 0;
          if (!this.isValidNumber(transCountValue) || transCountValue < 0) {
            return { valid: false, message: `第${i + 1}条物料数量必须大于0` };
          }

          // 验证数值范围
          if (prodCountValue > 999999) {
            return { valid: false, message: `第${i + 1}条物料重量超出范围` };
          }

          if (transCountValue > 999999) {
            return { valid: false, message: `第${i + 1}条物料数量超出范围` };
          }
        }
      }

      return { valid: true };
    },

    // 验证数字有效性
    isValidNumber(value) {
      return (
        value !== null &&
        value !== undefined &&
        !isNaN(value) &&
        isFinite(value)
      );
    },

    // 构建提交数据（旧格式，保留兼容性）
    buildSubmitData() {
      // 计算总重量和总数量
      const totalWeight = this.selectedMaterialRows.reduce(
        (sum, item) => sum + (Number(item.weight) || 0),
        0
      );
      const totalQuantity = this.selectedMaterialRows.reduce(
        (sum, item) => sum + (Number(item.quantity) || 0),
        0
      );

      return {
        ...this.formData,
        totalWeight: totalWeight,
        totalQuantity: totalQuantity,
        materialCount: this.selectedMaterialRows.length,
        materialList: this.selectedMaterialRows.map((item, index) => ({
          index: index + 1,
          materialName: item.materialName.trim(),
          materialCode: item.materialCode || "",
          brand: item.brand || "",
          spec: item.spec || "",
          picNo: item.picNo || "",
          prodCompany: item.prodCompany || "",
          weight: Number(item.weight) || 0,
          quantity: Number(item.quantity) || 0,
          contractCode: item.contractCode || "",
          remark: item.remark || "",
        })),
      };
    },

    // 构建提交数据（新API格式）
    buildNewSubmitData() {
      // 根据当前入库类型映射到对应的inType值
      const inTypeMap = {
        purchase: "采购入库",
        weigh: "检斤入库",
        manual: "人工入库",
      };

      // 构建主表数据
      const mainData = {
        id: null, // 新增时传null
        mainNo: "", // 系统自动生成
        inType: inTypeMap[this.currentInType] || "采购入库",
        warehouseCode:
          this.currentWarehouse?.warehouseCode || this.formData.warehouseId,
        warehouseName:
          this.currentWarehouse?.warehouseName || this.formData.warehouseName,
        ywDate: dateHelperApi.formatDateTime(this.formData.queryDate), // 后端要求格式：yyyy-MM-dd HH:mm:ss
        busMemo: "",
        details: [],
      };

      // 根据入库类型添加额外字段
      if (
        this.currentInType === "purchase" ||
        this.currentInType === "manual"
      ) {
        mainData.details = this.selectedMaterialRows.map((item, index) => {
          const detail = {
            ywDate: dateHelperApi.formatDateTime(this.formData.queryDate), // 后端要求格式：yyyy-MM-dd HH:mm:ss
            prodCount: Number(item.prodCount || 0),
            countUnit: "KG",
            warehouseCode:
              this.currentWarehouse?.warehouseCode || this.formData.warehouseId,
            warehouseName:
              this.currentWarehouse?.warehouseName ||
              this.formData.warehouseName,
          };
          // 检斤入库可以添加合同相关信息
          if (this.selectedContract) {
            mainData.poContractCode = this.selectedContract.contractCode;
            mainData.suppName = this.selectedContract.supplierName;
            (detail.materialCode = this.selectedContract.materialCode || ""),
              (detail.materialName = this.selectedContract.materialName.trim()),
              (detail.prodPrice = this.selectedContract.prodPrice || 0),
              (detail.budgetAmount = this.selectedContract.budgetAmount || 0),
              (detail.spec = this.selectedContract.spec || ""),
              (detail.brand = this.selectedContract.brand || ""),
              (detail.prodCompany = this.selectedContract.prodCompany || ""),
              (detail.categoryName = this.selectedContract.categoryName || ""),
              (detail.picNo = this.selectedContract.picNo || ""),
              (detail.batchNoSerial =
                this.selectedContract.batchNoSerial || ""),
              (detail.steelGradeName =
                this.selectedContract.steelGradeName || ""),
              (detail.standardName = this.selectedContract.standardName || ""),
              (detail.soDiameter = this.selectedContract.soDiameter || ""),
              (detail.soWidth = this.selectedContract.soWidth || ""),
              (detail.soThick = this.selectedContract.soThick || ""),
              //合同行号
              (detail.poContractDetailCode =
                this.selectedContract.poContractDetailCode || ""),
              (detail.soLength = this.selectedContract.soLength || "");
          } else {
            (detail.materialCode = item.materialCode || ""),
              (detail.materialName = item.materialName.trim());
          }
          // 添加辅助数量
          if (item.quantity || item.transCount || item.transCount === 0) {
            detail.transCount = Number(item.quantity || item.transCount || 0);
            detail.tranUnit = item.transUnit || "件";
          }

          return detail;
        });
      }
      if (this.currentInType === "weigh") {
        // 检斤入库可以添加合同相关信息
        if (this.selectedContract) {
          mainData.poContractCode = this.selectedContract.contractCode;
          mainData.suppName = this.selectedContract.supplierName;
        }

        // 将选中的检斤单信息填充到details中
        mainData.details = this.selectedWeightRows.map((item, index) => {
          const detail = {
            ywDate: this.formData.queryDate, // 后端要求格式：yyyy-MM-dd HH:mm:ss
            materialCode: this.selectedContract.materialCode || "",
            materialName: this.selectedContract.materialName || "",
            poContractDetailCode:
              this.selectedContract.poContractDetailCode || "",
            prodPrice: this.selectedContract.prodPrice || 0,
            prodCount: Number(item.netWeight) || 0, // 使用检斤单的实际重量
            countUnit: item.unit || "KG",
            transCount: Number(item.quantity) || 0, // 使用用户输入的数量（实时更新）
            tranUnit: item.transUnit || "件",
            spec: this.selectedContract.spec || "",
            brand: this.selectedContract.brand || "",
            prodCompany: this.selectedContract.prodCompany || "",
            categoryName: this.selectedContract.categoryName || "",
            picNo: this.selectedContract.picNo || "",
            batchNoSerial: this.selectedContract.batchNoSerial || "",
            steelGradeName: this.selectedContract.steelGradeName || "",
            standardName: this.selectedContract.standardName || "",
            soDiameter: this.selectedContract.soDiameter || "",
            soWidth: this.selectedContract.soWidth || "",
            soThick: this.selectedContract.soThick || "",
            soLength: this.selectedContract.soLength || "",
            //检斤单信息
            weightId: item.id || "",
            vehicleno: item.vehicleno || "",
          };
          return detail;
        });
      }

      return mainData;
    },

    // 显示提交确认
    showSubmitConfirm(submitData) {
      return new Promise((resolve) => {
        const materialCount = submitData.details
          ? submitData.details.length
          : 0;
        const totalWeight = submitData.details
          ? submitData.details.reduce(
              (sum, item) => sum + (Number(item.prodCount) || 0),
              0
            )
          : 0;
        const totalQuantity = submitData.details
          ? submitData.details.reduce(
              (sum, item) => sum + (Number(item.transCount) || 0),
              0
            )
          : 0;

        uni.showModal({
          title: "确认提交",
          content: `共${materialCount}条物料，总重量：${totalWeight}KG，总数量：${totalQuantity}，是否确认提交？`,
          confirmText: "确认",
          cancelText: "取消",
          success: (res) => {
            resolve(res.confirm);
          },
        });
      });
    },

    // 处理提交成功
    async handleSubmitSuccess(res) {
      uni.showToast({
        title: "入库单创建成功",
        icon: "success",
        duration: 1000,
      });

      // 记录成功日志
      console.log("入库单创建成功:", res.data);

      // 重置表单
      this.resetForm();
    },

    // 处理提交异常
    async handleSubmitException(error) {
      console.error("提交表单异常:", error);

      let errorMsg = "提交失败，请重试";

      // 网络错误处理
      if (error.message && error.message.includes("Network")) {
        errorMsg = "网络连接失败，请检查网络后重试";
      } else if (error.code === "ECONNABORTED") {
        errorMsg = "请求超时，请稍后重试";
      } else if (error.response && error.response.status) {
        switch (error.response.status) {
          case 400:
            errorMsg = "请求参数错误，请检查输入数据";
            break;
          case 401:
            errorMsg = "登录已过期，请重新登录";
            break;
          case 403:
            errorMsg = "没有权限执行此操作";
            break;
          case 500:
            errorMsg = "服务器错误，请稍后重试";
            break;
          default:
            errorMsg = `服务器错误 (${error.response.status})，请稍后重试`;
        }
      }

      uni.showModal({
        title: "提交失败",
        content: errorMsg,
        showCancel: false,
        confirmText: "知道了",
      });
    },
  },
};
</script>

<style scoped lang="scss">
@import "~@/pages/smart/scss/create.scss";
</style>
